import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../widgets/common_button.dart';
import '../services/app_state_service.dart';
import '../services/api_service.dart';
import 'contacts_page.dart';
import 'repair_orders_page.dart';

/// 应用首页
/// 展示主要功能模块和统计数据
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _selectedIndex = 0;
  
  final List<Widget> _pages = [
    const HomeTab(),
    const ContactsPage(),
    const RepairOrdersPage(),
    const ProfileTab(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _selectedIndex,
        children: _pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: _selectedIndex,
        onTap: (index) {
          setState(() {
            _selectedIndex = index;
          });
        },
        selectedItemColor: Theme.of(context).primaryColor,
        unselectedItemColor: Colors.grey[600],
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home_outlined),
            activeIcon: Icon(Icons.home),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.people_outline),
            activeIcon: Icon(Icons.people),
            label: '客户',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.assignment_outlined),
            activeIcon: Icon(Icons.assignment),
            label: '工单',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person_outline),
            activeIcon: Icon(Icons.person),
            label: '我的',
          ),
        ],
      ),
    );
  }
}

/// 首页标签页
class HomeTab extends StatefulWidget {
  const HomeTab({super.key});

  @override
  State<HomeTab> createState() => _HomeTabState();
}

class _HomeTabState extends State<HomeTab> {
  int _totalOrders = 0;
  int _completedOrders = 0;
  int _inProgressOrders = 0;
  int _pendingOrders = 0;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadStatistics();
  }

  @override
  void dispose() {
    // 清理资源，防止内存泄漏
    super.dispose();
  }

  /// 加载统计数据
  Future<void> _loadStatistics() async {
    if (!mounted) return;
    
    setState(() {
      _isLoading = true;
    });

    try {
      final appState = Provider.of<AppStateService>(context, listen: false);
      
      // 使用工单列表来统计
      final userTel = appState.currentUserTel ?? '';
      if (userTel.isNotEmpty) {
        print('开始加载工单统计数据，用户手机号: $userTel');
        final repairOrdersResponse = await ApiService.getAllRepairOrders(userTel);
        print('工单API响应: 成功=${repairOrdersResponse.isSuccess}, 消息=${repairOrdersResponse.message}');
        
        if (repairOrdersResponse.isSuccess && repairOrdersResponse.data != null) {
          final orders = repairOrdersResponse.data!;
          print('成功获取 ${orders.length} 个工单');
          if (mounted) {
            setState(() {
              _totalOrders = orders.length;
              _completedOrders = orders.where((order) => order.repairType == 'completed').length;
              _inProgressOrders = orders.where((order) => order.repairType == 'inProgress').length;
              _pendingOrders = orders.where((order) => order.repairType == 'pending').length;
            });
          }
          // 更新应用状态
          appState.setRepairOrders(orders);
        } else {
          print('工单API调用失败，使用本地数据');
          // 如果API调用失败，使用本地数据
          _loadLocalStatistics(appState);
        }
      } else {
        print('没有用户信息，使用本地数据');
        // 如果没有用户信息，使用本地数据
        _loadLocalStatistics(appState);
      }
    } catch (e) {
      print('加载统计数据失败: $e');
      // 错误处理，使用默认值
      if (mounted) {
        setState(() {
          _totalOrders = 0;
          _completedOrders = 0;
          _inProgressOrders = 0;
          _pendingOrders = 0;
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 加载本地统计数据
  void _loadLocalStatistics(AppStateService appState) {
    if (!mounted) return;
    
    setState(() {
      _totalOrders = appState.repairOrders.length;
      _completedOrders = appState.repairOrders.where((order) => order.repairType == 'completed').length;
      _inProgressOrders = appState.repairOrders.where((order) => order.repairType == 'inProgress').length;
      _pendingOrders = appState.repairOrders.where((order) => order.repairType == 'pending').length;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('首页'),
        backgroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadStatistics,
          ),
          IconButton(
            icon: const Icon(Icons.notifications_outlined),
            onPressed: () {
              // 通知功能
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 欢迎卡片
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Theme.of(context).primaryColor,
                    Theme.of(context).primaryColor.withOpacity(0.8),
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '欢迎使用QXXZS',
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    '汽车维修管理系统',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white.withOpacity(0.9),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 24.h),
            
            // 统计数据
            Text(
              '今日统计',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            SizedBox(height: 16.h),
            
            Row(
              children: [
                Expanded(
                  child: _buildStatCard(
                    '总工单',
                    _isLoading ? '...' : _totalOrders.toString(),
                    Icons.assignment,
                    Colors.blue,
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: _buildStatCard(
                    '已完成',
                    _isLoading ? '...' : _completedOrders.toString(),
                    Icons.check_circle,
                    Colors.green,
                  ),
                ),
              ],
            ),
            SizedBox(height: 12.h),
            
            Row(
              children: [
                Expanded(
                  child: _buildStatCard(
                    '进行中',
                    _isLoading ? '...' : _inProgressOrders.toString(),
                    Icons.hourglass_empty,
                    Colors.orange,
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: _buildStatCard(
                    '待处理',
                    _isLoading ? '...' : _pendingOrders.toString(),
                    Icons.pending,
                    Colors.red,
                  ),
                ),
              ],
            ),
            SizedBox(height: 24.h),
            
            // 快捷功能
            Text(
              '快捷功能',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            SizedBox(height: 16.h),
            
            GridView.count(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              crossAxisCount: 2,
              crossAxisSpacing: 12.w,
              mainAxisSpacing: 12.h,
              childAspectRatio: 1.5,
              children: [
                _buildQuickActionCard(
                  '添加客户',
                  Icons.person_add,
                  Colors.blue,
                  () {
                    // 跳转到客户管理页面的添加功能
                    DefaultTabController.of(context)!.animateTo(1);
                  },
                ),
                _buildQuickActionCard(
                  '新建工单',
                  Icons.add_task,
                  Colors.green,
                  () {
                    // 跳转到工单管理页面的添加功能
                    DefaultTabController.of(context)!.animateTo(2);
                  },
                ),
                _buildQuickActionCard(
                  '客户管理',
                  Icons.people,
                  Colors.purple,
                  () {
                    // 跳转到客户管理页面
                    DefaultTabController.of(context)!.animateTo(1);
                  },
                ),
                _buildQuickActionCard(
                  '工单管理',
                  Icons.assignment,
                  Colors.orange,
                  () {
                    // 跳转到工单管理页面
                    DefaultTabController.of(context)!.animateTo(2);
                  },
                ),
              ],
            ),
            SizedBox(height: 24.h),
            
            // 最近工单
            Text(
              '最近工单',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            SizedBox(height: 16.h),
            
            // 这里显示最近的工单列表
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                children: [
                  _buildRecentOrderItem('张三', '京A12345', '保养', '进行中'),
                  SizedBox(height: 12.h),
                  _buildRecentOrderItem('李四', '京B67890', '维修', '已完成'),
                  SizedBox(height: 12.h),
                  _buildRecentOrderItem('王五', '京C11111', '检查', '待处理'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatCard(String title, String value, IconData icon, Color color) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 24.sp),
          SizedBox(height: 8.h),
          Text(
            value,
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          Text(
            title,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQuickActionCard(String title, IconData icon, Color color, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: color, size: 28.sp),
            SizedBox(height: 8.h),
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: Colors.black87,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRecentOrderItem(String customerName, String carCode, String serviceType, String status) {
    Color statusColor;
    switch (status) {
      case '进行中':
        statusColor = Colors.orange;
        break;
      case '已完成':
        statusColor = Colors.green;
        break;
      case '待处理':
        statusColor = Colors.red;
        break;
      default:
        statusColor = Colors.grey;
    }

    return Row(
      children: [
        Container(
          width: 40.w,
          height: 40.w,
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Icon(
            Icons.person,
            color: Colors.grey[600],
            size: 20.sp,
          ),
        ),
        SizedBox(width: 12.w),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                customerName,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: Colors.black87,
                ),
              ),
              Text(
                '$carCode · $serviceType',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: statusColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(4.r),
          ),
          child: Text(
            status,
            style: TextStyle(
              fontSize: 12.sp,
              color: statusColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ],
    );
  }
}

/// 个人中心标签页
class ProfileTab extends StatelessWidget {
  const ProfileTab({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<AppStateService>(
      builder: (context, appState, child) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('个人中心'),
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16.w),
        child: Column(
          children: [
            // 用户信息卡片
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                children: [
                  CircleAvatar(
                    radius: 40.r,
                    backgroundColor: Theme.of(context).primaryColor,
                    child: Icon(
                      Icons.person,
                      size: 40.sp,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(height: 16.h),
                  Text(
                    appState.currentUsername ?? '用户',
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    appState.currentUserTel ?? '未设置手机号',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 24.h),
            
            // 功能列表
            _buildMenuSection([
              _buildMenuItem('设置', Icons.settings, () {}),
              _buildMenuItem('关于我们', Icons.info, () {}),
              _buildMenuItem('帮助中心', Icons.help, () {}),
              _buildMenuItem('意见反馈', Icons.feedback, () {}),
            ]),
            SizedBox(height: 24.h),
            
            // 退出登录
            CommonButton(
              text: '退出登录',
              onPressed: () async {
                // 显示确认对话框
                final confirmed = await showDialog<bool>(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: const Text('确认退出'),
                    content: const Text('确定要退出登录吗？'),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.of(context).pop(false),
                        child: const Text('取消'),
                      ),
                      TextButton(
                        onPressed: () => Navigator.of(context).pop(true),
                        child: const Text('确定'),
                      ),
                    ],
                  ),
                );
                
                if (confirmed == true) {
                  // 执行退出登录
                  await appState.logout();
                  // 跳转到登录页面
                  if (context.mounted) {
                    Navigator.of(context).pushReplacementNamed('/login');
                  }
                }
              },
              width: double.infinity,
              backgroundColor: Colors.red,
            ),
          ],
        ),
      ),
    );
      },
    );
  }

  Widget _buildMenuSection(List<Widget> items) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(children: items),
    );
  }

  Widget _buildMenuItem(String title, IconData icon, VoidCallback onTap) {
    return ListTile(
      leading: Icon(icon, color: Colors.grey[600]),
      title: Text(
        title,
        style: TextStyle(
          fontSize: 16.sp,
          color: Colors.black87,
        ),
      ),
      trailing: Icon(
        Icons.arrow_forward_ios,
        size: 16.sp,
        color: Colors.grey[400],
      ),
      onTap: onTap,
    );
  }
}
